package com.usian.controller;

import com.usian.pojo.Phone;
import com.usian.pojo.Stundet;
import com.usian.service.StudentService;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/us")
public class StudentController {

    @Autowired
    private StudentService userService;


    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    //导入excel
    @ResponseBody
    @RequestMapping("/importExcel")
    public String importExcel(MultipartFile file){
        //获取文件
        try {

            List<Stundet> stundets = new ArrayList<>();
            List<Phone> phones = new ArrayList<>();

            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            //获取工作表
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFSheet sheet1= workbook.getSheetAt(1);
            //获取到总行数 getLastRowNum
            //遍历
            for(int i=1;i<=sheet.getLastRowNum();i++){
                //获取到每一行的数据
                Row row = sheet.getRow(i);
                //获取每一行内容
                String  name = row.getCell(1).getStringCellValue();
                String sex = row.getCell(2).getStringCellValue();
                int age =(int) row.getCell(3).getNumericCellValue();
                Stundet student = new Stundet();
                student.setName(name);
                student.setSex(sex);
                student.setAge(age);

                stundets.add(student);
            }
            //遍历
            for(int i=1;i<=sheet1.getLastRowNum();i++){
                //获取到每一行的数据
                Row row = sheet1.getRow(i);
                //获取每一行内容
                String  dname = row.getCell(1).getStringCellValue();
                Phone phone=new Phone(null,dname);
                phones.add(phone);
            }
            userService.addPhone(phones);
            userService.addStudent(stundets);

            return "in";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        //使用poi进行遍历
        //遍历excel里的数据
        //写入到mysql数据库
    }
}
